<?php


namespace core;

use core\event\EventFactory;
use core\event\EventGroupMessage;
use core\event\EventMessage;
use core\mod\SysCommand;
use core\service\ModService;
use think\facade\Db;
use utils\Str;

class App {

    protected $input;

    protected $input_json;

    /**
     * @var array
     */
    protected $mods = [];

    /**
     * App constructor.
     */
    public function __construct() {
        // 设置MySQL配置
        Db::setConfig(config('database'));
        // 从模组服务中读取模组列表
        $this->mods = (new ModService())->getEnableMod();
        // 从配置文件中读取额外的模组列表
        $this->mods = array_merge($this->mods, config('mods') ?? []);
        // 固定加入系统模组
        array_push($this->mods, SysCommand::class);
        // 解析请求
        $this->input = file_get_contents('php://input');
        $this->input_json = json_decode($this->input, true);
    }

    public function handle() {
        if ($_SERVER['REQUEST_URI'] === '/post') {
            // 机器人上报
            static $HANDLE_METHODS = [
                EventGroupMessage::class => 'eventGroupMessage',
                EventMessage::class => 'eventMessage',
            ];
            $event = EventFactory::build($this->input_json);
            if (is_null($event)) {
                return;
            }
            foreach ($this->mods as $_mod) {
                (new $_mod())->{$HANDLE_METHODS[get_class($event)]}($event);
            }
        } else {
            // WEB控制器
            $splits = explode("/", ltrim($_SERVER['REQUEST_URI'], '/'));
            if (count($splits) < 3) {
                http_send(404);
                die();
            }
            // 把URI中的下划线格式转驼峰并且首字母大写
            $modName = $splits[0];
            $className = ucfirst(Str::camelize($splits[1]));
            $methodName = Str::camelize($splits[2]);
            if ($splits[0] === 'sys') {
                $class = "core\\mod\\{$className}";
            } else {
                $class = "app\\mod\\{$modName}\\{$className}";
            }
            if (!class_exists($class)) {
                http_send(404);
                die();
            }
            // 执行WEB
            $object = new $class();
            if (!method_exists($object, $methodName)) {
                http_send(404);
                die();
            }
            $object->{$methodName}();
        }
    }

}
